package com.zyz.sunliky.service.serviceImpl;

import cn.hutool.http.HttpRequest;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zyz.sunliky.mapper.erp.ErpMapper;
import com.zyz.sunliky.mapper.yunshu.PurchaseMapper;
import com.zyz.sunliky.service.PurchaseService;
import com.zyz.sunliky.util.LoginUtils;
import com.zyz.sunliky.util.UUIDUtils;
import org.apache.poi.hpsf.Decimal;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PurchaseServiceImpl implements PurchaseService {
    public static final org.slf4j.Logger logger = LoggerFactory.getLogger(PurchaseService.class);
    @Autowired
    PurchaseMapper purchaseMapper;
    @Autowired
    ErpMapper erpMapper;
    @Value("${spring.yunshuurl}")
    private String URL;

    @Override
    public Map getPrice(String supplierCode, String productNo) {
      //  Map map = new HashMap();
        Map<String, Object> map = purchaseMapper.getPrice(supplierCode,productNo);
        Map<String, Decimal> average= purchaseMapper.getQuantity(supplierCode,productNo);
        if (null != map){
            map.put("fndcgsl", average.get("fdhsl"));
            map.put("fpjjg", average.get("average"));
        }
        return map;
    }


    @Override
    public String updateRequestNo2(String fqqhdd) {
        //获取请求号最大值
        String pre=fqqhdd+"QQH"+ new SimpleDateFormat("yyMM").format(new Date());
        Integer maxvalue=purchaseMapper.getMaxNumber2(pre);
        if(maxvalue==null){
            maxvalue=0;
        }
        maxvalue++;
        String qqh = pre+new DecimalFormat("000000").format(maxvalue);
        return qqh;
    }

    /**创建采购请求**/
    @Override
    public String createCGQQ(String id) {
        /**查询表头**/
        List<Map<String,Object>> list_head=purchaseMapper.findModel_wkyfxqcgsq(id);
        if(list_head.isEmpty())throw new RuntimeException("没有此单据!");

        /**查询明细**/
        List<Map<String,Object>> list_mx=purchaseMapper.findfmxb_wkyfxqcgsq(id);
        /**查询用户名称**/
        String username=purchaseMapper.findUserName(id);
        if(StringUtils.isEmpty(username))throw new RuntimeException("用户不存在");
        JSONObject object = JSON.parseObject("{\n" +
                "  \"finishStart\":true,\n" +
                "  \"username\":\"admin\",\n" +
                "  \"workflowCode\":\"LC_CGQQ\"\n" +
                "}");
        String getuuid = UUIDUtils.getuuid();
        JSONObject data=new JSONObject();
        data.put("id", getuuid);
        JSONArray array=new JSONArray();
        Map map = list_head.get(0);
        String timestampString = map.get("fsqrq").toString();
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            // 将字符串解析为日期对象
            Date date = inputFormat.parse(timestampString);

            // 将日期对象格式化为指定格式的字符串
            String formattedDate = outputFormat.format(date);
            map.put("fsqrq",formattedDate);
            System.out.println("格式化后的日期：" + formattedDate);
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }
        data.put("fcgsqid",map.get("id"));
        data.put("fqqddbh",map.get("fqqddbh"));
        data.put("fqqh",map.get("fqqh"));

        for (Map<String, Object> listMx : list_mx) {
            JSONObject item=new JSONObject();
            listMx.forEach((key,value)->{
                item.put(String.valueOf(key),value);
            });
            map.forEach((key,value)->{
                item.put(String.valueOf(key),value);
            });
            /**特殊组件额外处理**/
            JSONArray array_creater = JSONArray.parseArray("[{\"id\":\""+map.get("fsqr")+"\",\"type\":3}]");
            item.put("fsqr",array_creater);
            item.remove("id");
            /**特殊组件额外处理结束**/
            array.add(item);
        }
        data.put("fmxb_cgqq",array);
        object.put("data",data);
        System.out.println(data);
        String s = object.toJSONString();
        String postResult = HttpRequest
                .post(URL+"/api/api/runtime/form/start_workflow")
                .header("Content-Type","application/json")
                .header("Authorization", "Bearer "+ LoginUtils.gettoken("1"))
                .body(s)
                .execute()
                .body();
//        updateRequestNo(getuuid);
        return postResult;
    }

    @Override
    public int getCount(String id, String type) {
        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(type)) {
            throw new IllegalArgumentException("产品编码和类型不能为空!");
        }
        int count = 0;
        // 1:生产 2:非生产
        switch (type) {
            case "1":
                count = erpMapper.getCountProduction(id);
                break;
            case "2":
                count = erpMapper.getCount(id);
                break;
            default:
                throw new IllegalArgumentException("无效的类型: " + type);
        }
        return count;
    }
}
